VB6 Math.Random to C# Code - c#

So I have the following code in VB6
string CharString = "KO0LPBGt7HU8NJI9acfDXESvgbYujmikolpw3MZWAQyhn6TFCR1q2Vzse4xdr5";
string DatePassword = string.Empty;
float x = VBMath.Rnd(-1);
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
x = VBMath.Rnd(-1);
VBMath.Randomize(dt.ToOADate());
for (int i=0; i<6; i++)
{
double y = Math.Truncate(VBMath.Rnd()*62);
DatePassword += CharString.Substring( Convert.ToInt32(y), 1);
}
I am having trouble converting this code over to C#. In particular how call randomize with the seed being a double. Here is my attempt in C#
string CharString = "KO0LPBGt7HU8NJI9acfDXESvgbYujmikolpw3MZWAQyhn6TFCR1q2Vzse4xdr5";
string DatePassword = string.Empty;
Random rnd = new Random(-1);
float x = rnd.Next();
DateTime dt = new DateTime(DateTime.Now.Year + DateTime.Now.Month + 1);
x = rnd.Next();
double z = rnd.NextDouble() * dt.ToOADate();
for (int i = 0; i < 6; i++)
{
x = rnd.Next();
double y = Math.Truncate(x * 62);
DatePassword += CharString.Substring(Convert.ToInt32(y), 1);
}

Related

Get RMS from FFT

I got an array of data voltages and I want to get the RMS value from the FFT that has been applied before to that data. I've seen that RMS in time domain should be equal to RMS(fft) / sqrt(nFFT) from Parseval's Theorem, but gives me different results. I'm using these functions:
1)FFT
public static VectorDPoint FFT(double[] trama, double samplingFreq)
{
double fs = samplingFreq; // Sampling frequency
double t1 = 1 / fs; // Sample time
int l = trama.Length; // Length of signal
// Time vector
//Vector t = Normal(0, l, 1) * t1;
//// Values vector
//Vector y = new Vector(trama);
// We just use half of the data as the other half is simetric. The middle is found in NFFT/2 + 1
int nFFT = (int)Math.Pow(2, NextPow2(l));
if (nFFT > 655600)
{ }
// Create complex array for FFT transformation. Use 0s for imaginary part
Complex[] samples = new Complex[nFFT];
for (int i = 0; i < nFFT; i++)
{
if (i >= trama.Length)
{
samples[i] = new MathNet.Numerics.Complex(0, 0);
}
else
{
samples[i] = new MathNet.Numerics.Complex(trama[i], 0);
}
}
ComplexFourierTransformation fft = new ComplexFourierTransformation(TransformationConvention.Matlab);
fft.TransformForward(samples);
ComplexVector s = new ComplexVector(samples);
s = s / l;
Vector f = (fs / 2.0) * Linspace(0, 1, (nFFT / 2) + 1);
VectorDPoint result = new VectorDPoint();
for (int i = 0; i < (nFFT / 2) + 1; i++)
{
result.Add(new DPoint(f[i], 2 * s[i].Modulus));
}
s = null;
f = null;
samples = null;
return result;
2) RMS
public static double RMSCalculate(double[] channelValues, int samplesNumber, double sampleRate, DateTime currentDate)
{
double[] times = new double[channelValues.Length];
double sampleTime = 0.0;
double period = 0;
times[0] = currentDate.Second + currentDate.Millisecond / 1000.0;
sampleTime = 1 / sampleRate; //s
// Limited samples
for (int i = 1; i < channelValues.Length; i++)
{
times[i] = times[i - 1] + sampleTime;
}
DPoint RMSValues = new DPoint();
RMSValues.Y = 0;
if (channelValues.Length == 1)
{
double x = channelValues[0];
double y = channelValues[0];
RMSValues = new DPoint(x, Math.Abs(y));
}
else
{
for (int i = 0; i < times.Length - 1; i++)
{
period = 0;
if (i + 1 < times.Length)
{
RMSValues.Y += channelValues[i + 1] * channelValues[i + 1] * (times[i + 1] - times[i]);
}
}
period = times[times.Length - 1] - times[0];
RMSValues.Y = RMSValues.Y / period;
RMSValues.Y = Math.Sqrt(RMSValues.Y);
}
return RMSValues.Y;
}

How to edit a asp.net chart X Axis label and only show date and not time

How do I remove the time from the X Axis in my chart.
My sql returns date only but my code adds the time again.
I have tried:
Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "##-##-##";
But no luck.
My current code:
Chart1.Visible = ddlChart.SelectedValue != "";
string query = string.Format(stest);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
int[] y = new int[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
Chart1.Series[0].Points.DataBindXY(x, y);
Chart1.Series[0].ChartType = SeriesChartType.Bar;
Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
Chart1.Legends[0].Enabled = true;
WORKING CODE - Thanks jstreet
Chart1.Visible = ddlChart.SelectedValue != "";
string query = string.Format(stest);
DataTable dt = GetData(query);
DateTime[] x = new DateTime [dt.Rows.Count];
int[] y = new int[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = Convert.ToDateTime(dt.Rows[i][0]);
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
Chart1.Series[0].Points.DataBindXY(x, y);
Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yyyy";
Chart1.Series[0].ChartType = SeriesChartType.Bar;
Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
Chart1.Legends[0].Enabled = true;
In a Bar chart (as opposed to a Column chart), the vertical axis is the AxisX, not AxisY. Also, avoid assigning a string to your AxisX. It is not necessary at all and may cause problems.
Use this:
Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yyyy";
or this:
Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yy";
EDIT:
Here's some sample code:
protected void Page_Load(object sender, EventArgs e)
{
DateTime[] x = new DateTime[3];
int[] y = new int[3];
for (int i = 0; i < 3; i++)
{
x[i] = DateTime.Now.AddDays(i);
y[i] = 10 * (i + 1);
}
Chart1.Series[0].Points.DataBindXY(x, y);
Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd-yy";
}
The following below should work
for (int i=0; i < dt.Rows.Count; i++)
{
DataRow row = dt.Rows[i];
x[i] = DateTime.ParseExact(row[0].ToString(), 'MM-dd-yy', CultureInfo.InvariantCulture);
y[i] = Convert.ToInt32(row[1]);
}

Neural Net - Feed Forward, Matrix Multiplication in C#

I'm attempting to make a Neural Network in C#, I based the design in a python code I made a while back. But somehow the end result is not the same.
I'm new to C# and I'm using it in Unity, so I have limitation to library uses.
In python numpy can do matrix multiplications with the numpy.dot() method. I Haven't found something similar in C#, especially in Unity. So I had to do it by hand.
The Python code:
import numpy as np
class NN:
def __init__(self, n_input, n_hidden_layers, n_hidden_nodes, n_output):
self.weights_hidden = []
for n in range(n_hidden_layers + 1):
if n == 0:
size = n_input, n_hidden_nodes
elif n == n_hidden_layers:
size = n_hidden_nodes, n_output
else:
size = n_hidden_nodes, n_hidden_nodes
self.weights_hidden.append(
np.random.random(size)
)
#staticmethod
def activation(x):
return np.tanh(x)
def feed_forward(self, ip):
input_values = (ip - np.mean(ip, axis=0)) / np.std(ip, axis=0)
for w, weights in enumerate(self.weights_hidden):
if w == 0:
result = input_values
result = np.array(
map(self.activation, result.dot(weights))
)
return result
ANN = NN(n_input=5, n_hidden_layers=2, n_hidden_nodes=3, n_output=1)
print ANN.feed_forward([1, 2, 3, 4, 5])
My attempt to convert it to C#.
using UnityEngine;
using System.Collections;
public class neural_net : MonoBehaviour {
int n_inputs;
int n_hidden_layers;
int n_hidden_nodes;
int n_outputs;
float[] inputs;
ArrayList hidden_weights;
ArrayList hidden_results;
float[] output_results;
public void init(int n_inputs, int n_hidden_layers, int n_hidden_nodes, int n_outputs){
this.n_inputs = n_inputs;
this.n_hidden_layers = n_hidden_layers;
this.n_hidden_nodes = n_hidden_nodes;
this.n_outputs = n_outputs;
this.hidden_weights = new ArrayList ();
this.hidden_results = new ArrayList ();
this.output_results = new float[n_outputs];
int rows;
int columns;
for (int h = 0; h < n_hidden_layers + 2; h++) {
if (h == 0){
// input -> hidden
rows = n_inputs;
columns = n_hidden_nodes;
}
else if(h == n_hidden_layers + 1){
// hidden -> output
rows = n_hidden_nodes;
columns = n_outputs;
}
else {
// hidden -> hidden
rows = n_hidden_nodes;
columns = n_hidden_nodes;
}
float[] hidden_result = new float[rows*columns];
hidden_results.Add(hidden_results);
float[,] target = new float[rows,columns];
string test = "";
for(int r = 0; r < rows; r++){
for(int c = 0; c < columns; c++){
target[r,c] = Random.Range(0.0f, 1.0f);
test += target[r,c] + ", ";
}
}
hidden_weights.Add(target);
}
}
float activation(float x){
// tanh(x);
return (1 - Mathf.Exp (-2 * x)) / (1 + Mathf.Exp (-2 * x));
}
float[] _dot_matrix(float[] results, float[,] weights){
float[] new_matrix = new float[weights.GetLength(1)];
string t0 = "";
for (int r = 0; r < weights.GetLength(1); r++){
float res = 0;
for (int c = 0; c < weights.GetLength(0); c++) {
res += results[c] * weights[c,r];
}
new_matrix[r] = res;
}
return new_matrix;
}
float[] _map_activation(float[] pre_results){
float[] results = new float[pre_results.Length];
for (int i = 0; i < results.Length; i++) {
results[i] = activation(pre_results[i]);
}
return results;
}
float[] feed_forward(){
int h;
for (h = 0; h < n_hidden_layers + 2; h++) {
float[] dot_matrix_result;
if(h == 0){
dot_matrix_result = _dot_matrix(inputs, (float[,])hidden_weights[h]);
}
else if (h == n_hidden_layers +1){
dot_matrix_result = _dot_matrix((float[])hidden_results[h-1], (float[,])hidden_weights[h]);
output_results = _map_activation(dot_matrix_result);
break;
}
else {
dot_matrix_result = _dot_matrix((float[])hidden_results[h-1], (float[,])hidden_weights[h]);
}
float[] result = _map_activation(dot_matrix_result);
hidden_results[h] = _map_activation(result);
}
return output_results;
}
float[] normalize_input(float[] inputs){
float sum = 0.0f;
for (int i = 0; i < inputs.Length; i++) {
sum += inputs[i] ;
}
float average = sum / inputs.Length;
float[] deviations = new float[inputs.Length];
for (int i = 0; i < inputs.Length; i++) {
deviations[i] = Mathf.Pow(inputs[i] - average,2);
}
float sum_deviation = 0;
for (int i = 0; i < deviations.Length; i++) {
sum_deviation += deviations[i];
}
float variance = sum_deviation / deviations.Length;
float std = Mathf.Sqrt (variance);
for (int i = 0; i < inputs.Length; i++) {
inputs[i] = (inputs[i] - average)/std;
}
return inputs;
}
public void start_net(float[] inputs){
this.inputs = normalize_input(inputs);
feed_forward ();
}
}
I run the net from other script using the init method and then the start_net() method.
I made a test with not random weights and fixed input data, but it didn't came to the same result as the python code.
What's wrong with the C# code?

c# feed a method with x and y values from a chart (polynomial calculation)

I have got this method to get a polynomial with my desired degree:
public static double[] Polyfit(double[] x, double[] y, int degree)
{
// Vandermonde matrix
var v = new DenseMatrix(x.Length, degree + 1);
for (int i = 0; i < v.RowCount; i++)
for (int j = 0; j <= degree; j++) v[i, j] = Math.Pow(x[i], j);
var yv = new DenseVector(y).ToColumnMatrix();
QR qr = v.QR();
// Math.Net doesn't have an "economy" QR, so:
// cut R short to square upper triangle, then recompute Q
var r = qr.R.SubMatrix(0, degree + 1, 0, degree + 1);
var q = v.Multiply(r.Inverse());
var p = r.Inverse().Multiply(q.TransposeThisAndMultiply(yv));
Console.WriteLine(p.Column(0).ToString());
return p.Column(0).ToArray();
}
How can I feed the method above with values from my chart (x and y)?
chart.Series[0].Points.... ?
I think you need this:
chart1.Series[0].YValueMembers
chart1.Series[0].XValueMember
The Points property is a getter, so you cannot set a new instance of DataPointCollection to it. You should however be able to access methods on the current DataPointCollection.
You could try something along the lines of:
chart.Series[0].Points.AddXY(double, double)
You would then iterate the array(s) and set the points manually.
MSDN DataPointCollection for more information.
A working solution is:
////generate polynomial of degree 4 fiting to the points
double[] arrayX = new double[chart.Series[0].Points.Count()];
double[] arrayY = new double[chart.Series[0].Points.Count()];
double[] arrayResult = { };
for (int i = 0; i < chart.Series[0].Points.Count(); i++)
{
arrayX[i] = chart.Series[0].Points[i].XValue;
arrayY[i] = chart.Series[0].Points[i].YValues[0];
}
arrayResult = Polyfit(arrayX, arrayY, 4);
foreach (double element in arrayResult)
{
MessageBox.Show(element.ToString());
}
double functionVarE = arrayResult[0];
double functionVarD = arrayResult[1];
double functionVarC = arrayResult[2];
double functionVarB = arrayResult[3];
double functionVarA = arrayResult[4];
double equationVar = 0;
//prepare the function series in the graph
if (chart.Series.IndexOf("function") < 0)
chart.Series.Add("function");
chart.Series[2].Points.Clear();
chart.Series[2].ChartType = SeriesChartType.Line;
for (int x = -500; x < 1000; x++) //hardcoding
{
equationVar = functionVarA * (Math.Pow(x, 4)) + functionVarB * (Math.Pow(x, 3)) + functionVarC * (Math.Pow(x, 2)) + functionVarD * x + functionVarE;
chart.Series[2].Points.AddXY(Convert.ToDouble(x), equationVar);
}
This is a working solution I coded. If you see any improvement feel free to tell me!

records on Access database are all the same in my code

I have written the following code to generate some security codes but these codes doesnt save correctly in access and all records are the same.although I traced my code and each time a different code is genrated but these diffrent codes doesnt save in access.just first code saves corectly and other records saves like first record
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = myconn;
label7.Text = "";
int[] s = new int[15];
int[] a = { 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
int[] b = { 0, 0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
int[] result1 = new int[13];
int[] result2 = new int[13];
int f = Convert.ToInt32(textBox1.Text);
int m = Convert.ToInt32(textBox2.Text);
double sum1 = 0;
double div1 = 0;
double sum2 = 0;
double div2 = 0;
int z = Convert.ToInt32(textBox2.Text) - Convert.ToInt32(textBox1.Text);
if (z >= 400)
{
Form1 h = new Form1();
h.Close();
}
while (f <= m)
{
int l = f;
for (int i = 0; i <= 3; i++)
{
s[i] = 2;
}
s[4] = 0;
s[5] = 1;
for (int i = 12; i >= 6; i--)
{
s[i] = l % 10;
l = l / 10;
}
for (int i = 0; i <= 12; i++)
{
result1[i] = s[i] * a[i];
result2[i] = s[i] * b[i];
sum1 += result1[i];
sum2 += result2[i];
}
div1 = sum1 / 11;
div2 = sum2 / 11;
double value1 = div1;
int r = (int)((value1 - (int)value1) * 10);
double value2 = div2;
int o = (int)((value2 - (int)value2) * 10);
if (r == 9)
{
s[13] = 0;
}
else
{
s[13] = r + 1;
}
if (o == 9)
{
s[14] = 0;
}
else
{
s[14] = o + 1;
}
string we = "";
for (int q = 0; q <= 14; q++)
{
we += s[q];
}
cmd.Parameters.AddWithValue("#SP", we);
cmd.CommandText = "INSERT INTO [Counter](SubscriptionCode)" + " VALUES (#SP)";
myconn.Open();
cmd.ExecuteNonQuery();
myconn.Close();
f++;
label7.Text += " \n ";
}
Check if the command is updated with the correct value on each iteration

Categories